package com.bluefox.modules.common.service.upload.proxy;

import com.bluefox.modules.common.service.upload.FileUpload;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @program: bluefox-parent
 * @description: 动态代理只是代理模式的一种
 * @author: Sun Feng
 * @create: 2020-06-30 16:26
 **/
@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "upload")
public class FileUploadProxy {

    private Map<String, List<String>> fileMap;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 文件上传代理方法
     *
     * @param multipartFile 上传的文件
     * @param extName       文件名称
     * @return 返回文件存储路径
     * @throws IOException
     */
    public String upload(MultipartFile multipartFile, String extName) throws IOException {

        //循环fileMap映射关系对象
        for (Map.Entry<String, List<String>> entry : fileMap.entrySet()) {
            List<String> suffixList = entry.getValue();

            for (String suffix : suffixList) {
                if (suffix.equalsIgnoreCase(extName)) {
                    String key = entry.getKey();
                    return applicationContext.getBean(key, FileUpload.class).upload(multipartFile, extName);
                }
            }
        }

        return null;
    }
}
